package com.gb.models.main;

import com.gb.models.main.utils.ResultMsg;
import com.gb.models.main.utils.ShiroUtils;
import com.gb.models.user.model.SysUserEntity;
import com.gb.models.user.service.SysUserService;
import com.gb.models.user.service.SysUserTokenService;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.util.Map;

/**
 * 主控制器
 *
 * @author lgoodbook@163.com
 * @version 1.0.0
 * @Date 2017-08-04 11:11
 */
@RestController
public class MainController {

    protected Logger log = LoggerFactory.getLogger(MainController.class);

    @Resource
    private Producer producer;

    @Resource
    private SysUserService userService;

    @Resource
    private SysUserTokenService userTokenService;

    /**
     * 登陆
     *
     * @param username
     * @param password
     * @param captcha
     * @return ResultMsg
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResultMsg userLogin(String username, String password, String  captcha) {
        ResultMsg result = new ResultMsg();
        String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
        if(!captcha.equalsIgnoreCase(kaptcha)){
            return new ResultMsg("验证码不正确");
        }
        SysUserEntity userEntity = userService.queryUserByUsernameAndPassword(username, password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        token.setRememberMe(true);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            //验证是否登录成功
            if (subject.isAuthenticated()) {
                if(userEntity != null) {
                    String tokenStr = userTokenService.updateToken(userEntity.getId(), userEntity.getEmail());
                    result.setData(tokenStr);
                    result.setState(Boolean.TRUE);
                }
            }
        }catch (Exception e){
            return new ResultMsg(e);
        }
        return result;
    }

    @RequestMapping("/logout")
    public ResultMsg logOut(HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        session.removeAttribute("user");
        return new ResultMsg();
    }

    @RequestMapping(value = "/captcha.jpg", method = RequestMethod.GET)
    public void captcha(HttpServletResponse response) throws Exception {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }
}
